package com.ruoyi.business.juheController;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.vo.R;
import com.ruoyi.system.protocol.IDynamicDataService;
import com.ruoyi.system.protocol.IDynamicSearchService;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.script.Script;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;

@RestController
@RequestMapping("/ownJuheApi")
public class juheIndexController {

    @Autowired
    @Qualifier("dynamicSearchJuheServiceImpl")
    private IDynamicSearchService dynamicSearchJuheServiceImpl;

    @Autowired
    private IDynamicDataService dynamicDataService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    @Qualifier("juheJdbcTemplate39")
    private JdbcTemplate juheJdbcTemplate39;


    @Autowired
    @Qualifier("juheJdbcTemplate182")
    private JdbcTemplate juheJdbcTemplate182;

    private final static String INDEX = "juhe";
    private final static String DYNAMIC_INDEX = "juhe_statistics";

    //每天凌晨1点执行一次
    @Scheduled(cron = "0 0 1 * * ?")
    @RequestMapping("/timedStatisticsTask")
    public void timedStatisticsTask(){
        Date date = DateUtils.addDays(new Date(), -1);
        String dayTime = DateUtils.parseDateToStr("yyyy-MM-dd", date);
        String startTime = dayTime + " 00:00:00";
        String endTime = dayTime + " 23:59:59";
        List<Map<String, Object>> addList = getEsRes(startTime, endTime);

        Map<String, Object> condition = new HashMap<>();
        condition.put("statistics_time", dayTime);
        Long dynamicDataCount = dynamicDataService.getDynamicDataCount(DYNAMIC_INDEX, condition);
        if(dynamicDataCount == 0){
            dynamicDataService.addBatchDynamicData(DYNAMIC_INDEX, addList);
        }
    }


    @RequestMapping("/timedStatisticsReq")
    public void timedStatisticsReq(){
        //从20231201开始统计
        Date date = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", "2023-10-02 00:00:00");
        Date maxDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", "2023-12-02 23:59:59");
        while (date.before(maxDate)){
            String startTime = DateUtils.parseDateToStr("yyyy-MM-dd 00:00:00", date);
            String endTime = DateUtils.parseDateToStr("yyyy-MM-dd 23:59:59", date);
            List<Map<String, Object>> addList = getEsRes(startTime, endTime);
            if(addList.size() > 0){
                Map<String, Object> condition = new HashMap<>();
                condition.put("statistics_time", startTime.substring(0, 10));
                Long dynamicDataCount = dynamicDataService.getDynamicDataCount(DYNAMIC_INDEX, condition);
                if(dynamicDataCount == 0){
                    dynamicDataService.addBatchDynamicData(DYNAMIC_INDEX, addList);
                }
            }
            date = DateUtils.addDays(date, 1);
        }
    }



    public List<Map<String, Object>> getEsRes(String startTime, String endTime){
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.must(new RangeQueryBuilder("createTime.keyword").gte(startTime).lte(endTime).format("yyyy-MM-dd HH:mm:ss"));

        String idOrCode = "doc['createTime.keyword'].value.substring(0,10)";
        Script script = new Script(Script.DEFAULT_SCRIPT_TYPE, Script.DEFAULT_SCRIPT_LANG, idOrCode, Collections.emptyMap());

        // Build the aggregation
        TermsAggregationBuilder createTimeAgg = AggregationBuilders.terms("createTimeAgg")
                .script(script).order(BucketOrder.key(false)).size(100);

        TermsAggregationBuilder channelIdAgg = AggregationBuilders.terms("channelIdAgg").field("channelId.keyword").size(10000);
        TermsAggregationBuilder typeAgg = AggregationBuilders.terms("typeAgg").field("type.keyword");
        createTimeAgg.subAggregation(channelIdAgg.subAggregation(typeAgg));

        Map<String, Object> map = dynamicSearchJuheServiceImpl.analysisQuery(INDEX, boolQueryBuilder, createTimeAgg);
        System.out.println(JSONObject.toJSONString(map));

        JSONObject mapJsonObj = JSONObject.parseObject(JSONObject.toJSONString(map));
        JSONObject createTimeAggRes = mapJsonObj.getJSONObject("createTimeAgg");
        List<Map<String, Object>> addList = new ArrayList<>();
        for(String timeKey: createTimeAggRes.keySet()){
            createTimeAggRes.getJSONObject(timeKey).getJSONObject("channelIdAgg").forEach((k,v)->{
                if(StringUtils.isBlank(k) || "null".equals(k)){
                    return;
                }
                JSONObject typeAggRes = createTimeAggRes.getJSONObject(timeKey).getJSONObject("channelIdAgg").getJSONObject(k).getJSONObject("typeAgg");
                typeAggRes.forEach((k1,v1)->{
                    Map<String, Object> addMap = new HashMap<>();
                    addMap.put("statistics_time", timeKey);
                    addMap.put("channel_id", k);
                    addMap.put("statistics_type", k1);
                    addMap.put("statistics_val", v1);
                    addList.add(addMap);
                });
            });
        }
        return addList;
    }
}
